<script setup lang="ts">
import { computed } from 'vue'
import type { FormProps } from 'ant-design-vue'

const props = withDefaults(defineProps<{
  // 表单配置
  formItems: {
    name: string
    label: string
    type: 'input' | 'select' | 'date' | 'upload'
    rules?: any[]
    options?: { label: string; value: any }[]
    props?: Record<string, any>
  }[]
  // 表单布局
  layout?: FormProps['layout']
  // 标签宽度
  labelWidth?: number
  // 表单数据
  modelValue: Record<string, any>
}>(), {
  layout: 'horizontal',
  labelWidth: 100
})

const emit = defineEmits(['update:modelValue'])

// 计算表单样式
const formItemStyle = computed(() => ({
  marginBottom: '24px',
  ...(props.layout === 'horizontal' ? {
    'label-width': `${props.labelWidth}px`
  } : {})
}))

// 处理表单项变化
const handleChange = (value: any, name: string) => {
  emit('update:modelValue', {
    ...props.modelValue,
    [name]: value
  })
}
</script>

<template>
  <a-form
    :model="modelValue"
    :layout="layout"
  >
    <a-form-item
      v-for="item in formItems"
      :key="item.name"
      :label="item.label"
      :name="item.name"
      :rules="item.rules"
      v-bind="formItemStyle"
    >
      <!-- 输入框 -->
      <a-input
        v-if="item.type === 'input'"
        v-model:value="modelValue[item.name]"
        v-bind="item.props"
        @change="(e) => handleChange(e.target.value, item.name)"
      />
      
      <!-- 选择框 -->
      <a-select
        v-else-if="item.type === 'select'"
        v-model:value="modelValue[item.name]"
        v-bind="item.props"
        @change="(value) => handleChange(value, item.name)"
      >
        <a-select-option
          v-for="option in item.options"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
      
      <!-- 日期选择 -->
      <a-date-picker
        v-else-if="item.type === 'date'"
        v-model:value="modelValue[item.name]"
        v-bind="item.props"
        @change="(date) => handleChange(date, item.name)"
      />
      
      <!-- 文件上传 -->
      <a-upload
        v-else-if="item.type === 'upload'"
        v-model:file-list="modelValue[item.name]"
        v-bind="item.props"
        @change="(info) => handleChange(info.fileList, item.name)"
      >
        <a-button>
          <upload-outlined /> 点击上传
        </a-button>
      </a-upload>
    </a-form-item>
  </a-form>
</template> 